<?php

/**
 * i18n actions.
 *
 * @package    chaihana
 * @subpackage i18n
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class i18nActions extends sfActions {

    public function executeIndex(sfWebRequest $request) {
        $this->search = $request->getParameter('search', '');
        $pager = new sfDoctrinePager('i18n_message', 20);
        $pager->setQuery(Doctrine::getTable('i18n_message')->getListForTranslationQuery($this->search));
        $pager->setPage($request->getParameter('page', 1));
        $pager->init();
        $this->pager = $pager;
        $this->languages = Doctrine::getTable('i18n_language')->findAll();
        $this->i18n_messages = $pager->getResults();
    }

    public function executeNew(sfWebRequest $request) {
        $i18n_message = new i18n_message();
        $trans_unit_id = $request->getParameter('trans_unit_id', null);
        $i18n_language_id = $request->getParameter('i18n_language_id', null);
        if (!$i18n_language_id) {
            $code = sfConfig::get('sf_default_culture');
            $language = Doctrine::getTable('i18n_language')->findOneByCode($code);
            $i18n_language_id = $language->getId();
            $trans_unit_id = $language->getNextTransUnitId();
        }
        $i18n_message->setTransUnitId($trans_unit_id);
        $i18n_message->setSource($request->getParameter('source', null));
        $i18n_message->seti18nLanguageId($i18n_language_id);
        $this->form = new i18n_messageForm($i18n_message);
    }

    public function executeCreate(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST));

        $this->form = new i18n_messageForm();

        $this->processForm($request, $this->form);

        $this->setTemplate('new');
    }

    public function executeEdit(sfWebRequest $request) {
        $this->forward404Unless($i18n_message = Doctrine_Core::getTable('i18n_message')->find(array($request->getParameter('id'))), sprintf('Object i18n_message does not exist (%s).', $request->getParameter('id')));
        $this->form = new i18n_messageForm($i18n_message);
    }

    public function executeUpdate(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($i18n_message = Doctrine_Core::getTable('i18n_message')->find(array($request->getParameter('id'))), sprintf('Object i18n_message does not exist (%s).', $request->getParameter('id')));
        $this->form = new i18n_messageForm($i18n_message);

        $this->processForm($request, $this->form);

        $this->setTemplate('edit');
    }

    public function executeDelete(sfWebRequest $request) {
        $request->checkCSRFProtection();

        $this->forward404Unless($i18n_message = Doctrine_Core::getTable('i18n_message')->find(array($request->getParameter('id'))), sprintf('Object i18n_message does not exist (%s).', $request->getParameter('id')));
        $i18n_message->delete();

        $this->redirect('i18n/index');
    }

    protected function processForm(sfWebRequest $request, sfForm $form) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $i18n_message = $form->save();

            $this->redirect('i18n/edit?id=' . $i18n_message->getId());
        }
    }

    public function executeImportFromFile(sfWebRequest $request) {
        $languages = Doctrine::getTable('i18n_language')->findAll();
        $this->logger = new ProcessLogger();
        foreach ($languages as $language) {
            $this->logger->addLog('neutral', 'Start processing language: ' . $language->getCode() . '...');
            $filepath = $language->getMessagePath();
            @$content = file_get_contents($filepath);
            if ($content) {

                $xml = new SimpleXMLElement($content);
                //echo '<pre>'; print_r($xml); echo '</pre>'; die();
                $tr = 'trans-unit';
                $attr = '@attributes';
                if ($xml) {
                    $deleted_count = Doctrine::getTable('i18n_message')->deleteAllWithLang($language);
                    $this->logger->addLog('db', 'Deleted <b>' . $deleted_count . '</b> messages with language = ' . $language->getCode() . ' from i18n_message database table');
                    $this->logger->addLog('neutral', 'Start adding messages to i18n_message database table...');
                    $messages = array();
                    foreach ($xml->file->body->$tr as $trans_unit) {
                        $messages[] = array(
                            'trans_unit_id' => (int) $trans_unit->attributes()->id,
                            'source' => (string) $trans_unit->source,
                            'target' => (string) $trans_unit->target
                        );
                    }
                    $language->addMessages($messages);
                    $this->logger->addLog('db', 'Added <b>' . count($messages) . '</b> messages with language = ' . $language->getCode() . ' to i18n_message database table');
                    $this->logger->addLog('neutral', 'Start adding messages to i18n_message database table...');
                } else {
                    $this->logger->addLog('error', 'Parsing error: Errors while parsing or empty file ' . $filepath);
                }
            } else {
                $this->logger->addLog('error', 'Import error: Error while getting ' . $filepath);
            }
            $this->logger->addLog('neutral', '...finish processing language: ' . $language->getCode());
            $this->logger->addLog('delimiter', '<hr/>');
        }
        $this->referer = $request->getReferer('i18n/index');
        if ($this->logger->getErrorsCount() > 0)
            $this->logger->emailLog();
    }

    public function executeExportToFile(sfWebRequest $request) {
        $languages = Doctrine::getTable('i18n_language')->findAll();
        $this->logger = new ProcessLogger();
        foreach ($languages as $language) {
            $this->logger->addLog('neutral', 'Start processing language: ' . $language->getCode() . '...');
            $filepath = $language->getMessagePath();
            $messages = $language->getMessages();
            if (count($messages) <= 0) {
                $this->logger->addLog('error', 'No messages for language ' . $language->getCode());
            } else {
                $content = $this->getPartial('xml', array('language' => $language, 'messages' => $messages));
                @$result = file_put_contents($filepath, $content);
                if ($result) {
                    $this->logger->addLog('db', '<b>' . count($messages) . '</b> messages with language = ' . $language->getCode() . ' writed to file: ' . $filepath);
                } else {
                    $this->logger->addLog('error', 'Error while writing to file: ' . $filepath);
                }
            }
            $this->logger->addLog('neutral', '...finish processing language: ' . $language->getCode());
            $this->logger->addLog('delimiter', '<hr/>');
        }
        $this->referer = $request->getReferer('i18n/index');
        if ($this->logger->getErrorsCount() > 0)
            $this->logger->emailLog();
    }

    public function executeClearCache(sfWebRequest $request) {
        $cacheDir_dev = sfConfig::get('sf_cache_dir') . DIRECTORY_SEPARATOR . 'frontend' . DIRECTORY_SEPARATOR . 'dev' . DIRECTORY_SEPARATOR;
        $cacheDir_prod = sfConfig::get('sf_cache_dir') . DIRECTORY_SEPARATOR . 'frontend' . DIRECTORY_SEPARATOR . 'prod' . DIRECTORY_SEPARATOR;

        //Clear cache
        $cache = new sfFileCache(array('cache_dir' => $cacheDir_dev));
        $cache->clean();
        $cache = new sfFileCache(array('cache_dir' => $cacheDir_prod));
        $cache->clean();
        $this->redirect($request->getReferer('i18n/index'));
    }

    public function executeTest(sfWebRequest $request) {
        @$content = file_get_contents('http://gdata.youtube.com/feeds/api/videos/NJiC6cA3dUA');
        if ($content) {
            $xml = new SimpleXMLElement($content);
            $namespaces = $xml->getNamespaces(TRUE);
            $group = $xml->children($namespaces['media'])->group;
            $namespaces = $group->getNamespaces(TRUE);
            $seconds = (int) $group->children($namespaces['yt'])->duration->attributes()->seconds;
            print_r($seconds);
        }

        die();
    }

}
